# -*- coding: utf-8 -*-
"""
评价相关表单

包含评价系统的所有表单验证：
- 提交评价表单
- 修改评价表单
- 评价筛选表单
- 统计查询表单
"""

from flask_wtf import FlaskForm
from wtforms import (
    SelectField, StringField, TextAreaField, HiddenField,
    SubmitField, IntegerField, DateField
)
from wtforms.validators import (
    DataRequired, Length, Optional, ValidationError, NumberRange
)
from datetime import datetime, date, timedelta

from app.models.evaluation import Evaluation
from app.models.reservation import Reservation
from app.models.user import User


class EvaluationForm(FlaskForm):
    """提交评价表单"""

    reservation_id = HiddenField(
        '预约ID',
        validators=[DataRequired(message='预约ID不能为空')]
    )

    rating = SelectField(
        '评分',
        choices=[
            ('', '请选择评分'),
            ('5', '⭐⭐⭐⭐⭐ 非常满意'),
            ('4', '⭐⭐⭐⭐ 满意'),
            ('3', '⭐⭐⭐ 一般'),
            ('2', '⭐⭐ 不满意'),
            ('1', '⭐ 很不满意')
        ],
        validators=[DataRequired(message='请选择评分')],
        render_kw={'class': 'form-select'}
    )

    comment = TextAreaField(
        '评价内容',
        validators=[
            Optional(),
            Length(max=500, message='评价内容不能超过500字')
        ],
        render_kw={
            'class': 'form-control',
            'rows': 4,
            'placeholder': '请详细描述您的体验和建议（可选）...'
        }
    )

    evaluator_type = HiddenField(
        '评价人类型',
        validators=[DataRequired(message='评价人类型不能为空')]
    )

    submit = SubmitField('提交评价', render_kw={'class': 'btn btn-primary'})

    def __init__(self, reservation=None, user_type=None, *args, **kwargs):
        super(EvaluationForm, self).__init__(*args, **kwargs)
        self.reservation = reservation
        self.user_type = user_type

        if reservation:
            self.reservation_id.data = str(reservation.id)

        if user_type:
            self.evaluator_type.data = user_type

    def validate_reservation_id(self, field):
        """验证预约ID"""
        if not field.data:
            return

        try:
            reservation_id = int(field.data)
            reservation = Reservation.query.get(reservation_id)

            if not reservation:
                raise ValidationError('预约记录不存在')

            if reservation.status != 'completed':
                raise ValidationError('只能对已完成的课程进行评价')

        except ValueError:
            raise ValidationError('无效的预约ID')

    def validate_rating(self, field):
        """验证评分"""
        if not field.data:
            return

        try:
            rating = int(field.data)
            if not (1 <= rating <= 5):
                raise ValidationError('评分必须在1-5之间')
        except ValueError:
            raise ValidationError('无效的评分')

    def validate_evaluator_type(self, field):
        """验证评价人类型"""
        if field.data not in ['student', 'coach']:
            raise ValidationError('无效的评价人类型')


class EditEvaluationForm(FlaskForm):
    """修改评价表单"""

    evaluation_id = HiddenField(
        '评价ID',
        validators=[DataRequired(message='评价ID不能为空')]
    )

    rating = SelectField(
        '评分',
        choices=[
            ('5', '⭐⭐⭐⭐⭐ 非常满意'),
            ('4', '⭐⭐⭐⭐ 满意'),
            ('3', '⭐⭐⭐ 一般'),
            ('2', '⭐⭐ 不满意'),
            ('1', '⭐ 很不满意')
        ],
        validators=[DataRequired(message='请选择评分')],
        render_kw={'class': 'form-select'}
    )

    comment = TextAreaField(
        '评价内容',
        validators=[
            Optional(),
            Length(max=500, message='评价内容不能超过500字')
        ],
        render_kw={
            'class': 'form-control',
            'rows': 4,
            'placeholder': '请详细描述您的体验和建议（可选）...'
        }
    )

    evaluator_type = HiddenField(
        '评价人类型',
        validators=[DataRequired(message='评价人类型不能为空')]
    )

    submit = SubmitField('更新评价', render_kw={'class': 'btn btn-warning'})

    def __init__(self, evaluation=None, user_type=None, *args, **kwargs):
        super(EditEvaluationForm, self).__init__(*args, **kwargs)
        self.evaluation = evaluation
        self.user_type = user_type

        if evaluation:
            self.evaluation_id.data = str(evaluation.id)

            # 根据用户类型设置初始值
            if user_type == 'student' and evaluation.student_rating:
                self.rating.data = str(evaluation.student_rating)
                self.comment.data = evaluation.student_comment
            elif user_type == 'coach' and evaluation.coach_rating:
                self.rating.data = str(evaluation.coach_rating)
                self.comment.data = evaluation.coach_comment

        if user_type:
            self.evaluator_type.data = user_type

    def validate_evaluation_id(self, field):
        """验证评价ID"""
        if not field.data:
            return

        try:
            evaluation_id = int(field.data)
            evaluation = Evaluation.query.get(evaluation_id)

            if not evaluation:
                raise ValidationError('评价记录不存在')

        except ValueError:
            raise ValidationError('无效的评价ID')

    def validate_rating(self, field):
        """验证评分"""
        if not field.data:
            return

        try:
            rating = int(field.data)
            if not (1 <= rating <= 5):
                raise ValidationError('评分必须在1-5之间')
        except ValueError:
            raise ValidationError('无效的评分')

    def validate_comment(self, field):
        """验证评价内容"""
        if field.data and len(field.data.strip()) == 0:
            field.data = None  # 空白内容设为None


class EvaluationFilterForm(FlaskForm):
    """评价筛选表单"""

    status = SelectField(
        '评价状态',
        choices=[
            ('', '全部状态'),
            ('pending', '待评价'),
            ('completed', '已评价'),
            ('mutual', '双方已评价')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    rating = SelectField(
        '评分筛选',
        choices=[
            ('', '全部评分'),
            ('5', '⭐⭐⭐⭐⭐ 5分'),
            ('4', '⭐⭐⭐⭐ 4分'),
            ('3', '⭐⭐⭐ 3分'),
            ('2', '⭐⭐ 2分'),
            ('1', '⭐ 1分')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    start_date = DateField(
        '开始日期',
        validators=[Optional()],
        render_kw={'class': 'form-control'}
    )

    end_date = DateField(
        '结束日期',
        validators=[Optional()],
        render_kw={'class': 'form-control'}
    )

    coach_id = SelectField(
        '教练筛选',
        choices=[],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    submit = SubmitField('筛选', render_kw={'class': 'btn btn-primary'})

    def __init__(self, user_id=None, user_type=None, *args, **kwargs):
        super(EvaluationFilterForm, self).__init__(*args, **kwargs)
        self.user_id = user_id
        self.user_type = user_type

        # 加载教练选项
        if user_id and user_type:
            self._load_coach_choices()

    def _load_coach_choices(self):
        """加载教练选项"""
        try:
            if self.user_type == 'student':
                # 获取学员关联过的教练
                evaluations = Evaluation.query.filter_by(student_id=self.user_id).all()
                coach_ids = list(set([e.coach_id for e in evaluations]))
                coaches = User.query.filter(
                    User.id.in_(coach_ids),
                    User.role == 'coach'
                ).all()
            else:
                # 管理员或其他角色可以看到所有教练
                coaches = User.query.filter_by(role='coach').all()

            self.coach_id.choices = [('', '全部教练')] + [
                (str(coach.id), coach.real_name or coach.username)
                for coach in coaches
            ]
        except Exception:
            self.coach_id.choices = [('', '全部教练')]

    def validate_end_date(self, field):
        """验证结束日期"""
        if field.data and self.start_date.data:
            if field.data < self.start_date.data:
                raise ValidationError('结束日期不能早于开始日期')

    def validate_rating(self, field):
        """验证评分筛选"""
        if field.data:
            try:
                rating = int(field.data)
                if not (1 <= rating <= 5):
                    raise ValidationError('无效的评分')
            except ValueError:
                raise ValidationError('无效的评分')


class QuickEvaluationForm(FlaskForm):
    """快速评价表单（用于弹窗）"""

    reservation_id = HiddenField(
        '预约ID',
        validators=[DataRequired(message='预约ID不能为空')]
    )

    rating = SelectField(
        '评分',
        choices=[
            ('', '请选择'),
            ('5', '⭐⭐⭐⭐⭐'),
            ('4', '⭐⭐⭐⭐'),
            ('3', '⭐⭐⭐'),
            ('2', '⭐⭐'),
            ('1', '⭐')
        ],
        validators=[DataRequired(message='请选择评分')],
        render_kw={'class': 'form-select form-select-sm'}
    )

    comment = TextAreaField(
        '评价内容',
        validators=[
            Optional(),
            Length(max=200, message='评价内容不能超过200字')
        ],
        render_kw={
            'class': 'form-control form-control-sm',
            'rows': 2,
            'placeholder': '请简要评价...'
        }
    )

    evaluator_type = HiddenField(
        '评价人类型',
        validators=[DataRequired(message='评价人类型不能为空')]
    )

    submit = SubmitField('提交', render_kw={'class': 'btn btn-primary btn-sm'})

    def validate_rating(self, field):
        """验证评分"""
        if not field.data:
            return

        try:
            rating = int(field.data)
            if not (1 <= rating <= 5):
                raise ValidationError('评分必须在1-5之间')
        except ValueError:
            raise ValidationError('无效的评分')


class BatchEvaluationForm(FlaskForm):
    """批量评价表单（管理员使用）"""

    reservation_ids = StringField(
        '预约ID列表',
        validators=[DataRequired(message='请输入预约ID列表')],
        render_kw={
            'class': 'form-control',
            'placeholder': '请输入多个预约ID，用逗号分隔'
        }
    )

    default_rating = SelectField(
        '默认评分',
        choices=[
            ('', '不设置默认评分'),
            ('5', '5分'),
            ('4', '4分'),
            ('3', '3分')
        ],
        validators=[Optional()],
        render_kw={'class': 'form-select'}
    )

    default_comment = TextAreaField(
        '默认评价内容',
        validators=[
            Optional(),
            Length(max=200, message='默认评价内容不能超过200字')
        ],
        render_kw={
            'class': 'form-control',
            'rows': 3,
            'placeholder': '批量设置的默认评价内容（可选）...'
        }
    )

    submit = SubmitField('批量创建评价', render_kw={'class': 'btn btn-warning'})

    def validate_reservation_ids(self, field):
        """验证预约ID列表"""
        if not field.data:
            return

        try:
            ids = [int(id_str.strip()) for id_str in field.data.split(',') if id_str.strip()]
            if not ids:
                raise ValidationError('请输入有效的预约ID')

            # 检查预约是否存在且已完成
            reservations = Reservation.query.filter(
                Reservation.id.in_(ids),
                Reservation.status == 'completed'
            ).all()

            if len(reservations) != len(ids):
                raise ValidationError('部分预约不存在或未完成')

        except ValueError:
            raise ValidationError('预约ID必须为数字')

    def validate_default_rating(self, field):
        """验证默认评分"""
        if field.data:
            try:
                rating = int(field.data)
                if not (1 <= rating <= 5):
                    raise ValidationError('默认评分必须在1-5之间')
            except ValueError:
                raise ValidationError('无效的默认评分')